# application/services/system/device.py
from application.device.hc.load import HcLoadService
from application.mapper.system.device import DeviceMapper
from typing import Dict, Any, List, Tuple
from application.models.system.device import SysDevice
from application.utils.res import models_to_dicts_camel, to_snake_case


class DeviceService:
    """设备服务层"""

    @staticmethod
    def get_device_list(
        page_num: int, page_size: int, conditions: Dict[str, Any] = None
    ) -> Tuple[List[Dict[str, Any]], int]:
        """
        分页获取设备列表
        :param page_num: 页码
        :param page_size: 每页数量
        :param conditions: 查询条件（如 deviceName, deviceModel, manufacturer 等）
        :return: (设备数据列表, 总数)
        """
        device_list, total = DeviceMapper.get_device_list(page_num, page_size, conditions)

        result_list = models_to_dicts_camel(device_list)

        return result_list, total

    @staticmethod
    def get_device_optionselect() -> List[Dict[str, Any]]:
        """
        获取设备下拉列表（用于前端选择）
        :return: 设备列表，格式为 [{value: id, label: name}]
        """
        devices = DeviceMapper.get_all_devices()  # 假设已添加此方法，或使用 get_device_list(1, 9999) 获取全部

        result_list = []
        for device in devices:
            result_list.append({
                "value": device.device_id,
                "label": device.device_name
            })

        return result_list

    @staticmethod
    def create_device(device_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        创建设备
        :param device_data: 设备数据字典（驼峰命名）
        :return: 创建后的设备数据（驼峰命名）
        """
        # 创建设备对象
        device = SysDevice()

        for key, value in device_data.items():
            snake_key = to_snake_case(key)
            if hasattr(device, snake_key):
                setattr(device, snake_key, value)

        created_device = DeviceMapper.create_device(device)
        return models_to_dicts_camel([created_device])[0]

    @staticmethod
    def update_device(device_id: int, device_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        更新设备
        :param device_id: 设备ID
        :param device_data: 设备数据字典（驼峰命名）
        :return: 更新后的设备数据（驼峰命名）
        """
        device = DeviceMapper.get_device_by_id(device_id)

        if not device:
            return None

        # 更新字段
        for key, value in device_data.items():
            snake_key = to_snake_case(key)
            if hasattr(device, snake_key):
                setattr(device, snake_key, value)

        updated_device = DeviceMapper.update_device(device)
        return models_to_dicts_camel([updated_device])[0]

    @staticmethod
    def delete_device(device_id: int) -> bool:
        """
        删除设备（软删除）
        :param device_id: 设备ID
        :return: 删除结果 True/False
        """
        device = DeviceMapper.get_device_by_id(device_id)

        if not device:
            return False

        try:
            DeviceMapper.delete_device(device)
            return True
        except Exception:
            return False
        

    @staticmethod
    def test_device(data) -> bool:
        """
        测试设备通讯
        :param data: 设备ID
        :return: 删除结果 True/False
        """
        if data.get('test_plan') == '1':
           # 测试方案: 汉测的 电压负载箱
           order = HcLoadService.get_voltage_load_order(data)
           
        elif data.get('test_plan') == '2':
           # 测试方案: 汉测的 电流负载箱
           order = HcLoadService.get_current_load_order(data)
    


        print("测试指令为", order)
        if data.get('communication_type') == '1':
            # 通讯方式: 串口
            print(1)
        
       